package com.inspur.edp.rule.dsl.core.function;

import java.math.BigDecimal;
import java.time.OffsetDateTime;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/12/31 15:06
 */
public class ConvertUtils {

    public static String convertToString(Object a) {
        if (a == null) {
            return "";
        } else {
            return a.toString();
        }
    }

    public static OffsetDateTime convertToDateTime(String dateTimeString) {
        return OffsetDateTime.parse(dateTimeString);
    }

    public static double convertToDouble(String str) {
        return Double.parseDouble(str);
    }

    public static int convertToInt(String str) {
        return Integer.parseInt(str);
    }

    public static BigDecimal convertToBigDecimal(String str) {
        return new BigDecimal(str);
    }

    public static String convertToCHNMoney(Number money) {
        return ChineseMoneyConverter.convert(money.doubleValue());
    }

    static class ChineseMoneyConverter {

        private static final char[] CN_NUMBERS = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
        private static final char[] CN_UNITS = {'分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'};

        public static String convert(double money) {
            StringBuilder result = new StringBuilder();
            int yuan = (int) Math.floor(money);
            int jiao = (int) Math.floor(money * 10 % 10); // 角
            int fen = (int) Math.floor(money * 100 % 10); // 分

            if (yuan > 0) {
                String yuanStr = String.valueOf(yuan);
                for (int i = 0; i < yuanStr.length(); i++) {
                    result.append(CN_NUMBERS[yuanStr.charAt(i) - '0']);
                    result.append(CN_UNITS[yuanStr.length() - 1 - i + 2]);
                }
            } else {
                result.append(CN_NUMBERS[0]);
            }
            if (jiao > 0) {
                result.append(CN_NUMBERS[jiao]);
                result.append(CN_UNITS[1]);
            } else if (jiao == 0 && result.charAt(result.length() - 1) == '零') {
                result.setCharAt(result.length() - 1, '零'); // 如果元部分为零，则万位应该是零
            } else if (result.charAt(result.length() - 1) != '零') {
                result.append('零'); // 如果前面没有零，需要补一个零
            }
            if (fen > 0) {
                result.append(CN_NUMBERS[fen]);
                result.append(CN_UNITS[0]);
            }
            return result.toString();
        }
    }

}
